package net.zhengxinyun.performance.service.indicators;

import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.dto.TownDTO;
import net.zhengxinyun.performance.entity.TownEntity;
import net.zhengxinyun.performance.entity.TownIndicatorsEntity;
import net.zhengxinyun.performance.filter.IndexFilter;
import net.zhengxinyun.performance.filter.TownFilter;
import net.zhengxinyun.performance.filter.TownIndicatorsFilter;
import net.zhengxinyun.performance.filter.TownScoreFilter;
import net.zhengxinyun.performance.mapper.Indicators.TownIndicatorsEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownScoreEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * @Auther: hyp
 * @Date: 2018/10/29 18:21
 */
@Service
public class TownIndicatorsServiceImpl implements TownIndicatorsService {

    private TownIndicatorsEntityMapper townIndicatorsEntityMapper;
    private TownMapper townMapper;
    private TownService townService;
    private TownScoreEntityMapper townScoreEntityMapper;

    @Autowired
    public TownIndicatorsServiceImpl(TownIndicatorsEntityMapper townIndicatorsEntityMapper, TownMapper townMapper, TownService townService, TownScoreEntityMapper townScoreEntityMapper) {
        this.townIndicatorsEntityMapper = townIndicatorsEntityMapper;
        this.townMapper = townMapper;
        this.townService = townService;
        this.townScoreEntityMapper = townScoreEntityMapper;
    }

    @Override
    @Transactional
    public String delete(TownIndicatorsEntity townIndicatorsEntity) {
        int a;
        TownIndicatorsEntity entity = townIndicatorsEntityMapper.selectByPrimaryKey(townIndicatorsEntity.getId());
        if ("一级指标".equals(entity.getIndexType())) {
            TownIndicatorsFilter townIndicatorsFilter = new TownIndicatorsFilter();
            townIndicatorsFilter.setSuperiorIndexId(entity.getId().toString());
            List<TownIndicatorsFilter> list = townIndicatorsEntityMapper.query(townIndicatorsFilter);
            for (TownIndicatorsFilter filter : list) {
                a = townIndicatorsEntityMapper.deleteByPrimaryKey(filter.getId());
                if (a == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "下属指标删除失败";
                }
                townScoreEntityMapper.deleteByIndexId(filter.getId().toString());
            }
        }
        a = townIndicatorsEntityMapper.deleteByPrimaryKey(townIndicatorsEntity.getId());
        if (a == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "删除失败,请联系管理员";
        }
        return "删除成功";
    }

    @Override
    @Transactional
    public String update(TownIndicatorsEntity townIndicatorsEntity, List<TownEntity> townList) {
        if ("二级指标".equals(townIndicatorsEntity.getIndexType())) {
//            List<TownEntity> list = Util.townUtil(townDTO);
            setSuperId(townIndicatorsEntity);
            int i = townIndicatorsEntityMapper.updateByPrimaryKeySelective(townIndicatorsEntity);
            if (i != 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "更新失败,请联系管理员";
            }
            int a;
            for (TownEntity townEntity : townList) {
                townEntity.setIndexId(townIndicatorsEntity.getId().toString());
                a = townMapper.updateByNameAndIndexId(townEntity);
                if (a != 1) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "更新失败,请联系管理员";
                }
            }
        } else {
            int i = townIndicatorsEntityMapper.updateByPrimaryKeySelective(townIndicatorsEntity);
            if (i != 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "更新失败,请联系管理员";
            }
        }
        return "更新成功";
    }

    /**
     * 单个指标添加
     *
     * @param townIndicatorsEntity
     * @param townList
     * @return
     */
    @Override
    @Transactional
    public String insert(TownIndicatorsEntity townIndicatorsEntity, List<TownEntity> townList) {
        //如果没有乡镇就直接添加
        if (townList == null) {
            setSuperId(townIndicatorsEntity);
            long i = townIndicatorsEntityMapper.insert(townIndicatorsEntity);
            if (i != 1) {
                //触发事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "添加失败,请联系管理员";
            }
            return "添加成功";
        }
        //如果是二级指标
        if ("二级指标".equals(townIndicatorsEntity.getIndexType())) {
            setSuperId(townIndicatorsEntity);
            long i = townIndicatorsEntityMapper.insert(townIndicatorsEntity);
            if (i != 1) {
                //触发事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "添加失败,请联系管理员";
            }
            townService.insert(townIndicatorsEntity, townList);
        }
        return "添加成功";
    }

    /**
     * 批量添加
     *
     * @param list
     * @return
     */
    @Override
    @Transactional
    public String ListInsert(List<TownDTO> list) {
        list = removeDuplicate(list);
        for (TownDTO townDTO : list) {
            TownIndicatorsEntity townIndicatorsEntity = townDTO.getTownIndicatorsEntity();
            List<TownEntity> townList = townDTO.getTownList();
            if ("二级指标".equals(townIndicatorsEntity.getIndexType())) {
                setSuperId(townIndicatorsEntity);
                long i = townIndicatorsEntityMapper.insert(townIndicatorsEntity);
                if (i != 1) {
                    //触发事务回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "添加失败,请联系管理员";
                }
                townService.insert(townIndicatorsEntity, townList);
            } else if ("一级指标".equals(townIndicatorsEntity.getIndexType())) {
                TownIndicatorsFilter filter = townIndicatorsEntityMapper.queryByNameAndTime(townIndicatorsEntity);
                if (filter != null) {
                    continue;
                }
                long i = townIndicatorsEntityMapper.insert(townIndicatorsEntity);
                if (i != 1) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "添加失败。请联系管理员";
                }
            }
        }
        return "添加成功";
    }

    /**
     * 查询二级指标及其对应的乡镇
     *
     * @param townIndicatorsFilter
     * @return
     */
    @Override
    public List<Map<String, Object>> querySec(TownIndicatorsFilter townIndicatorsFilter) {
        List<TownIndicatorsFilter> list = townIndicatorsEntityMapper.query(townIndicatorsFilter);
        List<Map<String, Object>> indexList = new ArrayList<>();
        TownIndicatorsEntity entity;
        for (TownIndicatorsFilter filter : list) {
            Map<String, Object> indexMap = new LinkedHashMap<>();
            indexMap.put("id", filter.getId());
            indexMap.put("indexType", filter.getIndexType());
            indexMap.put("leadUnit", filter.getLeadUnit());
            indexMap.put("indexName", filter.getIndexName());
            indexMap.put("responsibilityUnit", filter.getResponsibilityUnit());
            indexMap.put("direction", filter.getDirection());
            indexMap.put("weight", Double.parseDouble(filter.getWeight()));
            indexMap.put("dateTime", filter.getDateTime());
            indexMap.put("mainUnit", filter.getMainUnit());
            indexMap.put("endTime",filter.getEndTime());
            indexMap.put("warnType",filter.getWarnType());
            //把对应的上级指标名返回给前端
            if (StringUtils.isNotBlank(filter.getSuperiorIndexId())) {
                entity = townIndicatorsEntityMapper.selectByPrimaryKey(Long.valueOf(filter.getSuperiorIndexId()));
                if (entity != null) {
                    indexMap.put("superiorIndexId", entity.getIndexName());
                }
            }
            List<TownFilter> townList = townMapper.queryByIndexId(filter.getId().toString());
            for (TownFilter townFilter : townList) {
                if (StringUtils.isNotBlank(townFilter.getWeight())) {
                    indexMap.put(townFilter.getTownName(), Double.parseDouble(townFilter.getWeight()));
                } else {
                    indexMap.put(townFilter.getTownName(), null);
                }
            }
            indexList.add(indexMap);
        }
        return indexList;
    }

    @Override
    public List<Map<String, Object>> queryIndexMap(List<TownIndicatorsFilter> list) {
        List<Map<String, Object>> indexList = new ArrayList<>();
        TownIndicatorsFilter townIndicatorsFilter = new TownIndicatorsFilter();
        for (TownIndicatorsFilter filter : list) {
            HashMap indexMap = new HashMap();
            indexMap.put("firstName", filter);
            townIndicatorsFilter.setIndexType("");
            townIndicatorsFilter.setSuperiorIndexId(filter.getId().toString());
            List<TownIndicatorsFilter> secondIndexList = query(townIndicatorsFilter);
            indexMap.put("secondIndex", secondIndexList);
            indexList.add(indexMap);
        }
        return indexList;
    }

    @Override
    public List<TownIndicatorsFilter> query(TownIndicatorsFilter townIndicatorsFilter) {
        return townIndicatorsEntityMapper.query(townIndicatorsFilter);
    }

    @Override
    public Integer queryForCount(TownIndicatorsFilter townIndicatorsFilter) {
        return townIndicatorsEntityMapper.queryForCount(townIndicatorsFilter);
    }

    /**
     * 设置上级指标id
     *
     * @param townIndicatorsEntity
     * @return
     */
    public TownIndicatorsEntity setSuperId(TownIndicatorsEntity townIndicatorsEntity) {
        if (StringUtils.isNotBlank(townIndicatorsEntity.getSuperiorIndexId())) {
            String id = townIndicatorsEntityMapper.queryIdBySuperName(townIndicatorsEntity);
            townIndicatorsEntity.setSuperiorIndexId(id);
        }
        return townIndicatorsEntity;
    }

    @Override
    public List<TownIndicatorsFilter> indexTown(IndexFilter indexFilter) {
        List<TownIndicatorsFilter> list = null;
        if (StringUtils.isBlank(indexFilter.getDateTime()) && StringUtils.isBlank(indexFilter.getMonthTime())){
            TownScoreFilter townScoreFilter = townScoreEntityMapper.queryForNewTime();
            indexFilter.setDateTime(townScoreFilter.getDateTime());
            indexFilter.setMonthTime(townScoreFilter.getMonthTime());
            list = townIndicatorsEntityMapper.indexTown(indexFilter);
        }else {
            list = townIndicatorsEntityMapper.indexTown(indexFilter);
        }
//        Collections.sort(list, new Comparator<TownIndicatorsFilter>() {
//            @Override
//            public int compare(TownIndicatorsFilter o1, TownIndicatorsFilter o2) {
//                if (Integer.parseInt(o1.getRank()) > Integer.parseInt(o2.getRank())){
//                    return 1;
//                }else {
//                    return -1;
//                }
//            }
//        });
        return list;
    }

    @Override
    public List<Map<String, Object>> getIndexMap(List<TownIndicatorsFilter> list) {
        List<Map<String, Object>> indexList = new ArrayList<>();
        TownIndicatorsFilter countryIndicatorsFilter = new TownIndicatorsFilter();
        List<TownIndicatorsFilter> copyList = new ArrayList<>();
        for (TownIndicatorsFilter filter : list) {
            HashMap indexMap = new HashMap();
            indexMap.put("firstName", filter);
            countryIndicatorsFilter.setIndexType("");
            countryIndicatorsFilter.setSuperiorIndexId(filter.getId().toString());
            List<TownIndicatorsFilter> secondIndexList = query(countryIndicatorsFilter);
            Iterator<TownIndicatorsFilter> it = secondIndexList.iterator();
            while (it.hasNext()) {
                TownIndicatorsFilter c = it.next();
                if (StringUtils.isBlank(c.getLeadUnit())) {
                    copyList.add(c);
                    it.remove();
                }
            }
            for (TownIndicatorsFilter f:copyList) {
                countryIndicatorsFilter.setSuperiorIndexId(f.getId().toString());
                List<TownIndicatorsFilter> sonList = query(countryIndicatorsFilter);
                secondIndexList.addAll(sonList);
            }
            indexMap.put("secondIndex", secondIndexList);
            indexList.add(indexMap);
        }
        return indexList;
    }

    @Override
    public String setEndTime(List<TownIndicatorsEntity> list, String endTime,String warnType) {
        for (TownIndicatorsEntity entity:list) {
            entity.setEndTime(endTime);
            entity.setWarnType(warnType);
            int i = townIndicatorsEntityMapper.updateByPrimaryKeySelective(entity);
            if (i == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "设置失败";
            }
        }
        return "设置成功";
    }

    @Override
    public List<TownIndicatorsFilter> queryWarn(String today, String dateTime) {
        TownIndicatorsFilter townIndicatorsFilter = new TownIndicatorsFilter();
        townIndicatorsFilter.setEndTime(today);
        townIndicatorsFilter.setDateTime(dateTime);
        List<TownIndicatorsFilter> list = townIndicatorsEntityMapper.queryWarn(townIndicatorsFilter);
        return list;
    }

    /**
     * list集合根据上级指标id，指标名对元素去重
     *
     * @param list
     * @return
     */
    private List<TownDTO> removeDuplicate(List<TownDTO> list) {
        Set<TownDTO> set = new TreeSet<TownDTO>(new Comparator<TownDTO>() {
            @Override
            public int compare(TownDTO o1, TownDTO o2) {
                //字符串,则按照asicc码升序排列
                if (o1.getTownIndicatorsEntity().getIndexName().equals(o2.getTownIndicatorsEntity().getIndexName())
                        && o1.getTownIndicatorsEntity().getSuperiorIndexId().equals(o2.getTownIndicatorsEntity().getSuperiorIndexId())) {
                    return 0;
                }
                return 1;
            }
        });
        set.addAll(list);
        return new ArrayList<TownDTO>(set);
    }
}
